package handler

import (
	"beetle/internal/biz"
	"beetle/internal/model"
	"beetle/internal/pkg/constant"
	"beetle/internal/pkg/tool"
	"github.com/kataras/iris/v12"
	"strconv"
)

// redisSettingHandler 处理RedisSetting请求信息
type redisRecordHandler struct {
	srv biz.RedisRecordService
}

func NewRedisRecordHanler(srv biz.RedisRecordService) *redisRecordHandler {
	return &redisRecordHandler{srv}
}

// TODO 查询下拉列表
func (handler *redisRecordHandler) RequestModeOption(ctx iris.Context) {
	ctx.JSON(tool.Data(requestModeList))
}

func (handler *redisRecordHandler) SaveRecord(ctx iris.Context) {
	var record model.RedisRecord
	err := ctx.ReadJSON(&record)
	if err != nil {
		ctx.JSON(tool.Fail(err.Error()))
		return
	}
	err = handler.srv.Save(&record)
	if err != nil {
		ctx.JSON(tool.Fail(err.Error()))
		return
	}
	ctx.JSON(tool.Success())
}

func (handler *redisRecordHandler) UpdateRecord(ctx iris.Context) {
	var setting model.RedisRecord
	err := ctx.ReadJSON(&setting)
	if err != nil {
		ctx.JSON(tool.Fail(err.Error()))
		return
	}
	err = handler.srv.Update(&setting)
	if err != nil {
		ctx.JSON(tool.Fail(err.Error()))
		return
	}
	ctx.JSON(tool.Success())
}

func (handler *redisRecordHandler) RemoveRecord(ctx iris.Context) {
	id := ctx.Params().Get("id")
	pk, err := strconv.Atoi(id)
	if err != nil {
		if err != nil {
			ctx.JSON(tool.Fail(err.Error()))
			return
		}
	}
	err = handler.srv.Remove(pk)
	if err != nil {
		ctx.JSON(tool.Fail(err.Error()))
		return
	}
	ctx.JSON(tool.Success())
}

func (handler *redisRecordHandler) GetRecord(ctx iris.Context) {
	id := ctx.Params().Get("id")
	pk, err := strconv.Atoi(id)
	if err != nil {
		if err != nil {
			ctx.JSON(tool.Fail(err.Error()))
			return
		}
	}
	redisSetting, err := handler.srv.Find(pk)
	if err != nil {
		if err != nil {
			ctx.JSON(tool.Fail(err.Error()))
			return
		}
	}
	ctx.JSON(tool.Data(redisSetting))
}

func (handler *redisRecordHandler) PageRecord(ctx iris.Context) {

	var setting struct {
		model.RedisRecord
		model.Pager
	}

	err := ctx.ReadJSON(&setting)
	if err != nil {
		ctx.JSON(tool.Fail(err.Error()))
		return
	}

	list := handler.srv.Page(&setting.RedisRecord, setting.Pager)
	ctx.JSON(tool.Data(list))
}

func (handler *redisRecordHandler) Log(ctx iris.Context) {
	ctx.JSON(tool.Data("todo"))
}

type option struct {
	Label string
	Value string
}

var requestModeList = []option{
	{
		"HttpGet请求", string(constant.HttpGet),
	}, {
		"执行SQL", string(constant.SQL),
	}, {
		"JSON数据", string(constant.JSON),
	},
}
